package com.xo.xodemo.springsecurityconfig;

import com.alibaba.fastjson.JSONObject;
import netscape.javascript.JSObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
//把验证的结果放到springsecurity 默认的返回字段里
public class ValidateCodeFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException
    {

        response.setContentType("text/html");
        //得到请求地址
        String requestURI = request.getRequestURI();
        response.setCharacterEncoding("UTF-8");
        //判断是否是登录请求
        if (requestURI.equals("/tologin")) {
            if( request.getSession().getAttribute("circleCaptcha")==null){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("请重新登录");
                response.getWriter().flush();
            }
            //说明当前请求为登陆
            //1,得到登陆时用户输入的验证码
            String code1 = request.getSession().getAttribute("circleCaptcha").toString();
            String code = request.getParameter("code");
            if (StringUtils.hasText(code)) {
                if (code.equalsIgnoreCase(code1)) {
                    //说明验证码正确  直接放行
                    filterChain.doFilter(request, response);

                } else {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    //说明验证码不正确，返回登陆页面
                    response.getWriter().write("验证码错误");
                    response.getWriter().flush();
                }
            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("验证码不能为空");
                response.getWriter().flush();
            }
        } else {
            //说明不是登陆 直接放行到下一个过滤器
            filterChain.doFilter(request, response);
        }

    }
}